import i18next, { i18n as i18nType, InitOptions } from "i18next";
import { initReactI18next } from "react-i18next";
import { setHtmlPageLang, setLoadLocalePool } from "./helper";
import { store } from "@/redux/index";

async function createI18nOptions(): Promise<InitOptions> {
	const { language } = store.getState().global;
	const defaultLocal = await import(`./lang/${language}.ts`);

	setHtmlPageLang(language);
	setLoadLocalePool(loadLocalePool => {
		loadLocalePool.push(language);
	});

	return {
		resources: {
			[language]: {
				translation: defaultLocal.default || {}
			}
		},
		// default language
		fallbackLng: "en",
		debug: false,
		interpolation: {
			// not needed for react as it escapes by default
			escapeValue: false
		}
	};
}

// setup i18n instance with glob
export async function setupI18n() {
	const options = await createI18nOptions();
	i18next.use(initReactI18next).init(options);
	console.log("options", options);
	return i18next;
}

export const i18n: ReturnType<i18nType> = i18next;
